package com.cn.config;

import com.cn.pojo.Configuration;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.xml.parsers.SAXParser;
import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

public class XmlConfigBuilder {

    private Configuration configuration;

    // 初始化配置文件
    public XmlConfigBuilder() {
        this.configuration = new Configuration();
    }

    // 封装 Configuration 对象
    public Configuration parseConfig(InputStream in) throws DocumentException, PropertyVetoException {
        // 解析配置文件
        Document document = new SAXReader().read(in);
        // 获取根路径
        Element rootElement = document.getRootElement();
        // 从跟路径下查找标签
        List<Element> propertylist = rootElement.selectNodes("//property");
        // 用于存放数据源配置信息
        Properties properties = new Properties();
        for (Element element : propertylist) {
            String name = element.attributeValue("name");
            String value = element.attributeValue("value");
            properties.setProperty(name, value);
        }
        // 配置数据源
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
        comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        comboPooledDataSource.setUser(properties.getProperty("username"));
        comboPooledDataSource.setPassword(properties.getProperty("password"));
        // 设置数据源
        this.configuration.setDataSource(comboPooledDataSource);

        // 封装mapper中的内容
        List<Element> mapperdList = rootElement.selectNodes("//mapper");
        for (Element element : mapperdList) {
            String mapperPath = element.attributeValue("resource");
            XmlMapperBuilder xmlMapperBuilder = new XmlMapperBuilder(configuration);
            xmlMapperBuilder.parse(mapperPath);
        }

        return configuration;
    }

    public Configuration getConfiguration() {
        return configuration;
    }

    public void setConfiguration(Configuration configuration) {
        this.configuration = configuration;
    }
}
